#ifndef __UDP_SERVER_HPP__
#define __UDP_SERVER_HPP__

#include <iostream>
#include <string>
#include <memory>
#include <string.h>
#include <strings.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"
#include "Common.hpp"
#include "InetAddr.hpp"


using namespace LogModule;

const static int default_socketfd = -1;
// const static std::string default_ip = "127.0.0.1"; //表示本地主机
const static uint16_t default_port = 8080;         //1024以内的是熟知端口号，不能随意绑定

class UdpServer{
public:
    UdpServer(uint16_t port = default_port)
        :_socketfd(default_socketfd),
         //_ip(ip),
         //_port(port),
         _addr(port),
         _isrunning(false)
    {}
    void ServerInit()
    {
        //1.创建socket
        _socketfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_socketfd < 0){
            LOG(LogLevel::FATAL) << "socket failed: " << strerror(errno);
            Die(SOCKET_ERROR);
        }
        LOG(LogLevel::INFO) << "socket success, socketfd is " << _socketfd;

        //2.填充网络信息，把socket绑定ip地址和端口号
        //2.1 这里只是填充了结构体，并没有把socket信息设置进入内核
        // struct sockaddr_in address;
        // bzero(&address, sizeof(address));                 //将address全部清零再进行填充
        // address.sin_family = AF_INET;                     //协议家族
        // address.sin_port = htons(_port);                  //要绑定的端口号，这是要作为源端口号发送给对方的，即要发送到网络上，网络上的地址都是大端字节序，但每台主机大小端不确定，所以需要转换一下
        // // address.sin_addr.s_addr = inet_addr(_ip.c_str()); //要绑定的IP地址:string风格的ip->4字节的ip—>网络字节序
        // address.sin_addr.s_addr = INADDR_ANY;        //服务器用INADDR_ANY表示可以接受任何IP地址的请求

        //2.2 bind绑定：把socket信息设置进入内核！！！
        //int n = bind(_socketfd, CONV(&address), sizeof(address));
        int n = bind(_socketfd, _addr.NetAddr(), _addr.NetAddrLen());
        if(n != 0){
            LOG(LogLevel::FATAL) << "bind failed: " << strerror(errno);
            Die(BIND_ERROR);
        }
        LOG(LogLevel::INFO) << "bind success";
    }
    void ServerStart(){
        _isrunning = true;
        //服务器一般是不停的
        while(true){
            char inbuffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_socketfd, inbuffer, sizeof(inbuffer)-1, 0, CONV(&peer), &len);
            if(n > 0){
                //读取消息成功
                //1.需要知道消息内容 && 2.知道是谁发的
                inbuffer[n]=0;
                // uint16_t clientport = ntohs(peer.sin_port);
                // std::string clientip = inet_ntoa(peer.sin_addr);
                // std::string clientinfo = clientip+" : "+std::to_string(clientport)+" say# "+inbuffer;

                InetAddr client(peer);
                std::string clientinfo = client.Ip() +" :"+std::to_string(client.Port())+" say# "+inbuffer;

                LOG(LogLevel::INFO) << clientinfo;

                //3.给对方回消息
                std::string outbuffer = "echo# ";
                outbuffer += inbuffer;
                sendto(_socketfd, outbuffer.c_str(), outbuffer.size(), 0, CONV(&peer), sizeof(peer));
            }
        }
        _isrunning = false;
    }
    ~UdpServer(){
        if(_socketfd > default_socketfd){
            close(_socketfd);
        }
    }
private:
    int _socketfd;    //套接字的文件描述符
    InetAddr _addr;
    //uint16_t _port;   //服务器要绑定的端口号
    // std::string _ip;  //服务器要绑定的IP地址
    bool _isrunning;  //服务器是否启动
};

#endif